package com.sanctity.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.CountDownLatch;

/***
 * @belongsProject spring-cloud
 * @description <TODO description class purpose>
 * @author Sanct
 * @version 1.0.0
 * @create 2024/1/26 10:56
 **/
@Slf4j
@Component
public class ConfirmCallBack implements RabbitTemplate.ConfirmCallback{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private CountDownLatch latch;
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        latch =  new CountDownLatch(1);
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        if (ack){
            log.debug("Message confirmed: " + correlationData.getId());
            latch.countDown(); // 标记确认回调执行完成
        }else{
            log.debug("Message not confirmed: " + correlationData.getId() + " - " + cause);
            // 在 handleNack 中进行消息重发等处理
        }
    }
}
